package com.lzy.concertticket.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.lzy.concertticket.cache.OnlineUserCache;
import com.lzy.concertticket.model.entity.UserEntity;
import com.lzy.concertticket.model.req.LoginReq;
import com.lzy.concertticket.service.AuthService;
import com.lzy.concertticket.service.UserService;
import com.lzy.concertticket.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;

    @Override
    public String login(LoginReq loginReq) {

        //  通过账号查询用户
        UserEntity user = userService.getUserByAccount(loginReq.getAccount());
        //  校验用户是否存在
        Assert.notNull(user, "用户不存在");
        //  校验密码是否正确
        Assert.isTrue(user.getPassword().equals(loginReq.getPassword()), "密码错误");

        user.setPassword(null);
        user.setCreateTime(null);
        user.setUpdateTime(null);
        user.setBirthday(null);
        //  将user属性封装到map中, beanToMap
        Map<String, Object> userMap = BeanUtil.beanToMap(user);

        //  将用户信息封装到jwt令牌中
        String token = JwtUtil.createJWT(userMap);

        //  记录用户的登录状态
        OnlineUserCache.add(user);

        return token;
    }
}
